# -*- coding: utf-8 -*-
import datetime
import json
import random
import string

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from live_api.tools import utils_datetime
from live_api.tools.Output_Helper import *
from live_api.tools.sms import sendSmsCode
import live_api.tools.utils_file as ufile
import sys

reload(sys)
sys.setdefaultencoding('gbk')
@csrf_exempt
def sendsms(request):
    now = datetime.datetime.now()
    dtime = now.strftime('%Y-%m-%d %H:%M:%S')
    ret = ReturnJ()
    if request.method == 'POST':
        tel_number=request.POST.get("tel_number")
        ctype=request.POST.get("ctype")#注册,找回密码
        #1）根据ctype类型，确定发送内容，然后通过短信接口发出
        #2）将手机号、验证码、过期时间记录到redis
        data=sendSmsCode(tel_number)
        if data['code']!=2:
            ret.msg=data['msg']
        ret.smsid=data['smsid']
        res = HttpResponse(ret.toJson())
        res["Access-Control-Allow-Origin"] = "*"
        res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        res["Access-Control-Max-Age"] = "1000"
        res["Access-Control-Allow-Headers"] = "*"
        return res


@csrf_exempt
def uploadimage(request):
    ret = ReturnJ()
    try:
        if request.method == 'POST':
            ctype=request.POST.get("ctype")#注册,找回密码

            # 调用七牛上传图片
            if int(ctype)==0:#用户头像
                remotedir="cms_liuhua/user/"
            elif int(ctype)==1:#主播封面图
                remotedir="cms_liuhua/actor/background/"
            elif int(ctype)==2:#主播身份证照片
                remotedir="cms_liuhua/actor/card_pic/"
            elif int(ctype)==3:#视频封面图
                remotedir="cms_liuhua/video/"
            else:#其他
                remotedir="cms_liuhua/other/"
            ret_img = ufile.upload(request, 'img', remotedir)
            if ret_img['status']:
                # ret.img = 'http://p170makd4.bkt.clouddn.com/'+ret_img['db_img_path']
                # ret.img = 'http://liuhuaimage.xiancity.cn/'+ret_img['db_img_path']
                ret.img = datais.url_img+ret_img['db_img_path']
            else:
                # ret.code = 1010
                ret.msg = '图片上传失败!失败原因:%s'%(ret_img['error'])
                ret.img = ''
                ret.url_img = datais.url_img
    except Exception, e:
        # print(str(e))
        ret.code = 1011
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res
'''
@csrf_exempt
def input(request):
    from live_api.tools.UpLoad import UpLoad
    import os
    import time
    ret = ReturnJ()
    Upload = UpLoad()
    db = DB.getDB()
    rootdir = settings.BASE_DIR + '/live_api/static/old_user/users.csv'   # 文件路径

    remotedir = "cms_liuhua/user/"
    list = os.listdir(rootdir)  # 列出文件夹下所有的目录与文件
    print len(list)
    for localimg in list:
        nichname = localimg.split(".", 1)[0]  # 图片名
        localimg = os.path.join(rootdir, localimg)   # 文件路径
        todaytime = int(time.time())  # 时间戳
        phototime = 'img%s' % todaytime  # 图片时间
        photo_last = str(localimg).split('.')[-1]  # 图片格式
        phototime = "%s.%s" % (phototime, photo_last)  # 图片重新命名
        remotepath = os.path.join(remotedir, phototime)  # 拼接路径到七牛

        try:
            Upload.put(remotepath, localimg)  # 上传到七牛云
            id = maxid("user", "id")
            if id == 59:
                 id = id + 1
            print id
            neteas_euser_info = p.createUserId(accid="new_liuhua_%s" % id, name=nichname, icon=datais.url_img + remotepath)  # 上传到网易
            if neteas_euser_info['code'] == 200:
                accid = neteas_euser_info['info']['accid']
                token = neteas_euser_info['info']['token']
                try:
                    cdate = int(time.time())
                    tel_number = '12345678910'
                    cpwd = "123456"
                    gender = 2
                    ctype = 0
                    address = 'beijing'
                    img = remotepath
                    signature = '机器人'
                    share_code = '10000'
                    par1 = 'test'
                    par2 = 'test'
                    id_account = '12345678910'
                    age = 26
                    is_used = 1
                    real_name = 'test'
                    salt = ''.join(random.sample(string.ascii_letters + string.digits, 6))
                    nickname = '%s%s' % (salt, id)
                    cname = nickname
                    sql = "insert into user(id,cname,cpwd,ctype,accid,token,nickname,gender,age,tel_number,address,img,signature,share_code,par1,par2,cdate,is_used,id_account,real_name) values(%s,'%s',%s,%s,'%s','%s','%s',%s,%s,%s,'%s','%s','%s',%s,'%s','%s',%s,%s,%s,'%s')" % (
                        id, cname, cpwd, ctype, accid, token, nickname, gender, age, tel_number, address, img,signature, share_code, par1, par2, cdate, is_used, id_account, real_name)
                    print sql
                    n = db.execute(sql)
                except Exception, e:
                    ret.msg = "数据库操作异常!" + str(e)
                    return HttpResponse(ret.toJson())
            ret.msg = '成功'
        except Exception, e:
            ret.code = 1010
            ret.msg = str(e)
    return HttpResponse(ret.toJson())

'''

@csrf_exempt
def input(request):
    ret = ReturnJ()
    db = DB.getDB()
    old_user = settings.BASE_DIR + '/live_api/static/old_user/users.csv'
    import csv
    users = []
    with open(old_user, 'r') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            users.append(
                {'real_name': 'old_user', 'id_account': 12345678901, 'is_used': 1, 'par2': 'old_user', 'par1': 1,
                 'ctype': 0, 'id': row[0], 'userName': row[1], 'password': row[2], 'neteaseAccount': row[3],
                 'neteaseToken': row[4], 'nickName': row[5], 'gender': row[6], 'age': row[7], 'phoneNum': row[8],
                 'address': row[9], 'picUrl': row[10], 'signature': row[11], 'shareCode': row[12], 'regTime': row[13]})
    id = maxid("user", "id")
    neteas_euser_info = {}
    # neteas_euser_info = p.createUserId(accid="new_liuhua_%s" % id, name=users[3]['userName'])  # 上传到网易
    neteas_euser_info['code'] = 200
    if neteas_euser_info['code'] == 200:
        # accid = neteas_euser_info['info']['accid']
        accid = 'qwertyuiowertyu'
        token = 'wqertyu3456y7'
        # token = neteas_euser_info['info']['token']
    # try:
        cdate = int(time.time())
        tel_number = users[3]['phoneNum']
        cpwd = users[3]['password']
        gender = users[3]['gender']
        ctype = 0
        address = users[3]['address']
        img = datais.header
        signature = users[3]['signature']
        share_code = users[3]['shareCode']
        par1 =users[3]['par1']
        par2 =users[3]['par2']
        id_account = '12345678910'
        age = users[3]['age']
        is_used = 1
        real_name =users[3]['real_name']
        salt = ''.join(random.sample(string.ascii_letters + string.digits, 6))
        nickname = users[3]['nickName']
        cname = users[3]['userName']
        sql = "insert into user(id,cname,cpwd,ctype,accid,token,nickname,gender,age,tel_number,address,img,signature,share_code,par1,par2,cdate,is_used,id_account,real_name) values(%s,'%s',%s,%s,'%s','%s','%s',%s,%s,%s,'%s','%s','%s',%s,'%s','%s',%s,%s,%s,'%s')" % (
            id, cname, cpwd, ctype, accid, token, nickname, gender, age, tel_number, address, img,signature, share_code, par1, par2, cdate, is_used, id_account, real_name)
        # n = db.execute(sql)
        # /**********************************创建用户的user_finance记录************************************************************/
        # id1 = maxid("user_finance", "id")
        # sql = sqlr(
        #     "select id_user from user_finance where user_finance.id_user=%s",
        #     id1)
        # n, rows = db.query(sql)
        # if n == 0:
        #     sql = sqlr(
        #         "insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values(%s,%s,0,0,0,0)",id1,id1)
        #     print 11111111111111111111,sql
                # db.execute(sql)
    # except Exception, e:
    #     ret.msg = "数据库操作异常!" + str(e)
    #     return HttpResponse(ret.toJson())
    ret.msg = users[3]
    ret.code = 200
    return HttpResponse(ret.toJson())












